<?php
/**
 * User: congtang
 * Email: congtang@anjuke.com
 * Date: 15-9-24
 * Time: 下午2:02
 */

function requestGet($url, $cookie = null, $auth = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    if($cookie){
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if($auth){
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $auth);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

function requestPost($url, $post_data, $cookie = null,$auth = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11');
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    if($cookie){
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if($auth){
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $auth);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

$data = $_POST;
$cookie = null;
$auth = null;
if(!empty($data['cookie'])){
    $cookie = $data['cookie'];
    unset($data['cookie']);
}
if(!empty($data['auth'])){
    $auth = $data['auth'];
    unset($data['auth']);
}

if($data['datatype'] == 'params'){
    foreach(parse_url($data['url']) as $key => $val){
        if($key == 'query'){
            $val = !empty($data['params']) ? $val . '&' . $data['params'] : $val;
            parse_str($val, $datas);
            echo "\n\n";
            foreach($datas as $key2 => $val2){
                echo $key2 . ': ' . $val2 . "\n";
            }
        }else{
            echo $key . ': ' . $val . "        ";
        }
    }
    exit();
}

if($data['type'] == 'POST'){
    parse_str($data['params'], $datas);
    $res = requestPost($data['url'], $datas, $cookie, $auth);
}elseif($data['type'] == 'RAW'){
    $data['params'] = str_replace(' ', '', $data['params']);
    $res = requestPost($data['url'], $data['params'], $cookie, $auth);
}else{
    $res = requestGet($data['url'].'?'.$data['params'], $cookie, $auth);
}



if($data['datatype'] == 'json'){
    $rs = json_decode($res, true);
    print_r($rs);
}else{
    echo $res;
}
